﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MapWindowDocking
{
    public class ProjectionFileReader
    {
        public IEnumerable<ProjectionGroup> ReadFromFile(string path)
        {
            List<ProjectionGroup> groups = new List<ProjectionGroup>();

            StreamReader reader = new StreamReader(path);
            string line;
            ProjectionGroup group = null;
            while ((line = reader.ReadLine()) != null)
            {
                //Check if we are at a header.
                if (line.Contains("---"))
                {
                    if (group == null)
                    {
                        int first = line.IndexOf("---", 0) + 3;
                        int last = line.IndexOf("---", first + 3);

                        string name = line.Substring(first, last - first).Trim();
                        group = new ProjectionGroup(name);
                    }
                    else
                    {
                        //Store the current group.
                        groups.Add(group);
                        string name = line.Replace("---", "");
                        group = new ProjectionGroup(name);
                    }
                }

                // If we are not a header and the line is blank, the we should be looking at projection group.
                if (!line.Contains("---") && !String.IsNullOrEmpty(line) && group != null)
                {
                    Projection proj = new Projection(line, line);
                    group.Projections.Add(proj);
                }

            }

            // Add the last group the collection.
            groups.Add(group);
            reader.Close();

            return groups;
        }
    }

    public class ProjectionGroup
    {
        public ProjectionGroup(String groupName)
        {
            this.Name = groupName;
            this.Projections = new List<Projection>();
        }

        public String Name { get; set; }
        public List<Projection> Projections { get; set; }
    }

    public class Projection
    {
        public Projection(String projectionName, String coordsysString)
        {
            this.Name = projectionName;
            this.CoordsysString = coordsysString;
        }

        public String Name { get; set; }
        public String CoordsysString { get; set; }
    }
}
